package com.zjlanyun.eplus.view.report.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.aihook.tableview.lib.TableDataAdapter;
import com.aihook.tableview.lib.TableFixHeaders;
import com.yanzhenjie.nohttp.rest.Response;
import com.zjlanyun.eplus.R;
import com.zjlanyun.eplus.network.WebApi;
import com.zjlanyun.eplus.nohttp.HttpRequest;
import com.zjlanyun.eplus.nohttp.SimpleHttpListener;
import com.zjlanyun.eplus.view.report.ReportActivity;
import com.zjlanyun.eplus.view.report.adapter.GalleryAdapter;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_ACTION;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_JSON_DATA;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_TF_JSON_CONDITION;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_TF_JSON_TABLE;
import static com.zjlanyun.eplus.view.report.UtilConstants.MODEL_ID;
import static com.zjlanyun.eplus.view.report.UtilConstants.SHOW_TABLE;
import static com.zjlanyun.eplus.view.report.UtilConstants.SQL_CONDITION;
import static com.zjlanyun.eplus.view.report.UtilConstants.TABLE_ACTION;

/**
 * 作者：韩笑 on 2017/6/23 0023 16:58
 * <p>
 * 作用：表格，用于柱形图饼状图的表格显示
 */


public class TableFragment extends Fragment implements GalleryAdapter.ItemClickListener{
    private static final String TAG = "TableFragment";
    private TableFixHeaders mTableFixHeaders;
    private RecyclerView mRecyclerView;//横向RecyclerView
    private LinearLayout recyclerview_layout;
    ArrayList<ArrayList<String>> mList;
    private String modelId;
    public static TableFragment newInstance(String info, String type) {
        Bundle args = new Bundle();
        TableFragment fragment = new TableFragment();
        args.putString(MODEL_ID, info);
        args.putString(SQL_CONDITION, type);
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.table_fragement, null);
        Log.d(TAG, getArguments().getString(MODEL_ID) + "/" + getArguments().getString(SQL_CONDITION));
        mTableFixHeaders = (TableFixHeaders)view.findViewById(R.id.table);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.id_recyclerview_horizontal);
        recyclerview_layout = (LinearLayout) view.findViewById(R.id.recyclerview_layout);
        modelId = getArguments().getString(MODEL_ID);
        initData();
        return view;
    }
    
    /**
    *该方法为 当Fragment展现于屏幕上调用，防止用户在统计图页面加载统计图时同时加载该页面
    *@author xiao.han
    *created at 2017/6/23 0023 17:03
    */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            //相当于Fragment的onResume
            modelId = getArguments().getString(MODEL_ID);
            initData();
        } else {
            //相当于Fragment的onPause

        }
    }

    /**
    *加载数据
    *@author xiao.han
    *created at 2017/6/23 0023 17:04
    */
    public void initData(){
        //设置横向recycleView
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);


        //获取表格数据
        HttpRequest client = new HttpRequest(getActivity(), WebApi.api());
        client.getRequest().add(KEY_ACTION, TABLE_ACTION);
        client.getRequest().add(MODEL_ID, modelId);
     //   Log.d(TAG,"TABLE_ACTION:"+TABLE_ACTION + "modelId:" +modelId + "api"+WebApi.api());
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                super.onSucceed(what, response);
                Log.d(TAG,"返回的数据:"+response.get().toString());
                parseData(response.get().toString());
            }
        });
    }

    /**
    *解析数据，封装数据
    *@author xiao.han
    *created at 2017/6/23 0023 17:08
    */
    public void parseData(String Json){
        try{
            mList = new ArrayList<>();
            JSONObject jsonObject = new JSONObject(Json);
            JSONArray jsonArray = jsonObject.getJSONArray(KEY_JSON_DATA);
            //获取条件
            JSONObject condition = (JSONObject) jsonArray.get(0);
            JSONArray conditionJSONArray = condition.getJSONArray(KEY_TF_JSON_CONDITION);
            List<Map<String,String>> tdomainList = new ArrayList<>();
            //条件
            for (int i = 0 ; i < conditionJSONArray.length() ; i ++){
                Log.d(TAG,"condition:" + conditionJSONArray.get(i).toString());
                if (conditionJSONArray.get(i).toString() == null || conditionJSONArray.get(i).toString().equals("")) {
                    recyclerview_layout.setVisibility(View.GONE);
                    mRecyclerView.setVisibility(View.GONE);
                }else {
                    Map<String, String> map = new HashMap<>();
                    map.put("PropertyName", conditionJSONArray.get(i).toString());
                    map.put("tdomain", "tdomain:" + conditionJSONArray.get(i).toString());
                    tdomainList.add(map);
                }
            }
            GalleryAdapter mAdapter = new GalleryAdapter(tdomainList);
            mAdapter.setOnClickListener(this);
            mRecyclerView.setAdapter(mAdapter);

            //获取展示数据
            JSONObject table = (JSONObject) jsonArray.get(1);
            JSONArray resultJsonArray = table.getJSONArray(KEY_TF_JSON_TABLE);
            for (int i = 0; i< resultJsonArray.length(); i++){
                ArrayList<String> arrayList = new ArrayList<>();
                JSONArray a =(JSONArray) resultJsonArray.get(i);
                for (int j = 0 ; j < a.length() ; j ++){
                    arrayList.add(j,a.get(j).toString());
                }
                mList.add(arrayList);
            }
            myHandle.sendEmptyMessage(SHOW_TABLE);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    Handler myHandle = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == SHOW_TABLE){
                TableDataAdapter tableDataAdapter = new TableDataAdapter(getActivity(), mList, 40, 16);
                mTableFixHeaders.setAdapter(tableDataAdapter);
            }
        }
    };

    @Override
    public void itemClick(int position, String PropertyName, String sql,String viewModel,String model_id) {
        Log.d(TAG,"点击了上方菜单,postion = "+ position + "....PropertyName = " + PropertyName + "....sql = " + sql);
    }

}
